<template>
  <el-container style="height: 100vh; border: 5px solid #eee; display: flex;">
    <el-aside width="200px" style="background-color: #f3f4f6; color: #333; text-align: left;">
      <el-menu :unique-opened="true" @select="handleMenuSelect" style="border-right: none;">
        <el-menu-item index="memberAgeDistribution">
          <i class="el-icon-s-custom" style="color: orange"></i>会员年龄分布
        </el-menu-item>
        <el-menu-item index="memberGenderDistribution">
          <i class="el-icon-s-custom" style="color: orange"></i>会员性别分布
        </el-menu-item>
        <el-menu-item index="memberGrowthTrend">
          <i class="el-icon-s-custom" style="color: orange"></i>会员增长趋势
        </el-menu-item>
        <el-menu-item index="courseReservationCount">
          <i class="el-icon-s-custom" style="color: orange"></i>课程预约次数
        </el-menu-item>
        <el-menu-item index="coachReservationCount">
          <i class="el-icon-s-custom" style="color: orange"></i>教练预约次数
        </el-menu-item>
        <el-menu-item index="equipmentQuantity">
          <i class="el-icon-s-custom" style="color: orange"></i>设备数量
        </el-menu-item>
        <el-menu-item index="cardPurchaseCount">
          <i class="el-icon-s-custom" style="color: orange"></i>卡种购买统计
        </el-menu-item>
        <el-menu-item index="evaluateSubmission">
          <i class="el-icon-s-custom" style="color: orange"></i>评价提交情况
        </el-menu-item>
        <el-menu-item @click="exportAllData">
          <i class="el-icon-download" style="color: orange"></i>转储数据报表
        </el-menu-item>
        <el-menu-item index="home" @click="goToHome">
          <i class="el-icon-house" style="color: orange"></i>返回首页
        </el-menu-item>
      </el-menu>
    </el-aside>
    <main class="main" style="flex: 1; display: flex; justify-content: center; align-items: center; overflow: auto; padding: 20px;">
      <div class="report-content" style="width: 100%; max-width: 1200px;">
        <div v-if="currentView === 'memberAgeDistribution'">
          <h2>会员年龄分布</h2>
          <div ref="ageChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'memberGenderDistribution'">
          <h2>会员性别分布</h2>
          <div ref="genderChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'memberGrowthTrend'">
          <h2>会员增长趋势</h2>
          <div ref="growthChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'courseReservationCount'">
          <h2>课程预约次数</h2>
          <div ref="courseReservationChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'coachReservationCount'">
          <h2>教练预约次数</h2>
          <div ref="coachReservationChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'equipmentQuantity'">
          <h2>设备数量</h2>
          <div ref="equipmentChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'cardPurchaseCount'">
          <h2>卡种购买统计</h2>
          <div ref="cardPurchaseChart" style="width: 100%; height: 400px;"></div>
        </div>
        <div v-if="currentView === 'evaluateSubmission'">
          <h2>评价提交情况</h2>
          <el-table :data="evaluateRatingDistribution" style="width: 100%">
            <el-table-column prop="rating" label="评价等级"></el-table-column>
            <el-table-column prop="count" label="数量"></el-table-column>
          </el-table>
          <h3>好评、中评、差评中出现次数最多的内容</h3>
          <el-table :data="topEvaluateContents" style="width: 100%">
            <el-table-column prop="rating" label="评价等级"></el-table-column>
            <el-table-column prop="content" label="内容"></el-table-column>
            <el-table-column prop="count" label="出现次数"></el-table-column>
          </el-table>
        </div>
      </div>
    </main>
  </el-container>
</template>

<script>
import * as XLSX from 'xlsx';
import axios from 'axios';
import * as echarts from 'echarts';
export default {
  data() {
    return {
      currentView: 'memberAgeDistribution', // 默认显示会员年龄分布
      ageChart: null,
      genderChart: null,
      growthChart: null,
      courseReservationChart: null,
      coachReservationChart: null,
      equipmentChart: null,
      cardPurchaseChart: null,
      evaluateRatingDistribution: [],
      topEvaluateContents: [],
    };
  },
  methods: {
    goToHome() {
      this.$router.push("/home");
    },
    handleMenuSelect(index) {
      this.currentView = index;
      this.fetchDataForCurrentView();
    },
    fetchDataForCurrentView() {
      switch (this.currentView) {
        case 'memberAgeDistribution':
          this.fetchMemberAgeDistribution();
          break;
        case 'memberGenderDistribution':
          this.fetchMemberGenderDistribution();
          break;
        case 'memberGrowthTrend':
          this.fetchMemberGrowthTrend();
          break;
        case 'courseReservationCount':
          this.fetchCourseReservationCount();
          break;
        case 'coachReservationCount':
          this.fetchCoachReservationCount();
          break;
        case 'equipmentQuantity':
          this.fetchEquipmentQuantity();
          break;
        case 'cardPurchaseCount':
          this.fetchCardPurchaseCount();
          break;
        case 'evaluateSubmission':
          this.fetchEvaluateRatingDistribution();
          this.fetchTopEvaluateContents();
          break;
        default:
          break;
      }
    },
    fetchMemberAgeDistribution() {
      axios.get('/api/report/member/ageDistribution').then((response) => {
        const data = response.data;
        this.initAgeChart(data);
      }).catch((error) => {
        console.error('Error fetching member age distribution:', error);
      });
    },
    fetchMemberGenderDistribution() {
      axios.get('/api/report/member/genderDistribution').then((response) => {
        const data = response.data;
        this.initGenderChart(data);
      }).catch((error) => {
        console.error('Error fetching member gender distribution:', error);
      });
    },
    fetchMemberGrowthTrend() {
      axios.get('/api/report/member/growthTrend').then((response) => {
        const data = response.data;
        this.initGrowthChart(data);
      }).catch((error) => {
        console.error('Error fetching member growth trend:', error);
      });
    },
    fetchCourseReservationCount() {
      axios.get('/api/report/course/reservationCount').then((response) => {
        const data = response.data;
        this.initCourseReservationChart(data);
      }).catch((error) => {
        console.error('Error fetching course reservation count:', error);
      });
    },
    fetchCoachReservationCount() {
      axios.get('/api/report/coach/reservationCount').then((response) => {
        const data = response.data;
        this.initCoachReservationChart(data);
      }).catch((error) => {
        console.error('Error fetching coach reservation count:', error);
      });
    },
    fetchEquipmentQuantity() {
      axios.get('/api/report/equipment/quantity').then((response) => {
        const data = response.data;
        this.initEquipmentChart(data);
      }).catch((error) => {
        console.error('Error fetching equipment quantity:', error);
      });
    },
    fetchCardPurchaseCount() {
      axios.get('/api/report/card/purchaseCount').then((response) => {
        const data = response.data;
        this.initCardPurchaseChart(data);
      }).catch((error) => {
        console.error('Error fetching card purchase count:', error);
      });
    },
    fetchEvaluateRatingDistribution() {
      axios.get('/api/report/ratingDistribution').then((response) => {
        this.evaluateRatingDistribution = response.data;
        console.log('Evaluate Rating Distribution:', this.evaluateRatingDistribution);
      }).catch((error) => {
        console.error('Error fetching evaluate rating distribution:', error);
      });
    },
    fetchTopEvaluateContents() {
      axios.get('/api/report/topContents').then((response) => {
        this.topEvaluateContents = response.data;
        console.log('Top Evaluate Contents:', this.topEvaluateContents);
      }).catch((error) => {
        console.error('Error fetching top evaluate contents:', error);
      });
    },
    initAgeChart(data) {
      if (this.ageChart) {
        this.ageChart.dispose();
      }
      this.ageChart = echarts.init(this.$refs.ageChart);

      const ages = data.map((item) => item.age || '未知年龄');
      const counts = data.map((item) => item.count || 0);

      const option = {
        title: {
          text: '会员年龄分布',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: ages,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '会员数量',
            type: 'bar',
            data: counts,
          },
        ],
      };

      this.ageChart.setOption(option);
    },
    initGenderChart(data) {
      if (this.genderChart) {
        this.genderChart.dispose();
      }
      this.genderChart = echarts.init(this.$refs.genderChart);

      const genders = data.map((item) => item.gender);
      const counts = data.map((item) => item.count);

      const option = {
        title: {
          text: '会员性别分布',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          data: genders,
        },
        series: [
          {
            name: '性别',
            type: 'pie',
            radius: '50%',
            data: genders.map((gender, index) => ({
              value: counts[index],
              name: gender,
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };

      this.genderChart.setOption(option);
    },
    initGrowthChart(data) {
      if (this.growthChart) {
        this.growthChart.dispose();
      }
      this.growthChart = echarts.init(this.$refs.growthChart);

      const months = data.map((item) => item.month);
      const counts = data.map((item) => item.count);

      const option = {
        title: {
          text: '会员增长趋势',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: months,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '会员数量',
            type: 'line',
            data: counts,
          },
        ],
      };

      this.growthChart.setOption(option);
    },
    initCourseReservationChart(data) {
      if (this.courseReservationChart) {
        this.courseReservationChart.dispose();
      }
      this.courseReservationChart = echarts.init(this.$refs.courseReservationChart);

      const courseNames = data.map((item) => item.courseName);
      const counts = data.map((item) => item.count);

      const option = {
        title: {
          text: '课程预约次数',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: courseNames,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '预约次数',
            type: 'bar',
            data: counts,
          },
        ],
      };

      this.courseReservationChart.setOption(option);
    },
    initCoachReservationChart(data) {
      if (this.coachReservationChart) {
        this.coachReservationChart.dispose();
      }
      this.coachReservationChart = echarts.init(this.$refs.coachReservationChart);

      const coachNames = data.map((item) => item.coachName);
      const counts = data.map((item) => item.count);

      const option = {
        title: {
          text: '教练预约次数',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: coachNames,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '预约次数',
            type: 'bar',
            data: counts,
          },
        ],
      };

      this.coachReservationChart.setOption(option);
    },
    initEquipmentChart(data) {
      if (this.equipmentChart) {
        this.equipmentChart.dispose();
      }
      this.equipmentChart = echarts.init(this.$refs.equipmentChart);

      const equipmentNames = data.map((item) => item.name);
      const quantities = data.map((item) => item.quantity);

      const option = {
        title: {
          text: '设备数量',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: equipmentNames,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            data: quantities,
          },
        ],
      };

      this.equipmentChart.setOption(option);
    },
    initCardPurchaseChart(data) {
      if (this.cardPurchaseChart) {
        this.cardPurchaseChart.dispose();
      }
      this.cardPurchaseChart = echarts.init(this.$refs.cardPurchaseChart);

      const cardTypes = data.map((item) => item.cardType);
      const counts = data.map((item) => item.count);

      const option = {
        title: {
          text: '卡种购买统计',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          data: cardTypes,
        },
        series: [
          {
            name: '卡种购买数量',
            type: 'pie',
            radius: '50%',
            data: cardTypes.map((cardType, index) => ({
              value: counts[index],
              name: cardType,
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };

      this.cardPurchaseChart.setOption(option);
    },
    exportAllData() {
      const wb = XLSX.utils.book_new();

      const requests = [
        axios.get('/api/report/member/ageDistribution'),
        axios.get('/api/report/member/genderDistribution'),
        axios.get('/api/report/member/growthTrend'),
        axios.get('/api/report/course/reservationCount'),
        axios.get('/api/report/coach/reservationCount'),
        axios.get('/api/report/equipment/quantity'),
        axios.get('/api/report/card/purchaseCount'),
        axios.get('/api/report/evaluate/submission', {
          params: {
            page: 1,
            size: 10,
          },
        }),
        axios.get('/api/report/ratingDistribution'),
        axios.get('/api/report/topContents'),
      ];

      Promise.all(requests).then((responses) => {
        const ageData = responses[0].data;
        const genderData = responses[1].data;
        const growthData = responses[2].data;
        const courseData = responses[3].data;
        const coachData = responses[4].data;
        const equipmentData = responses[5].data;
        const cardData = responses[6].data;
        const evaluateData = responses[7].data;
        const ratingDistribution = responses[8].data;
        const topContents = responses[9].data;

        const ageSheet = XLSX.utils.json_to_sheet(ageData);
        XLSX.utils.book_append_sheet(wb, ageSheet, '会员年龄分布');

        const genderSheet = XLSX.utils.json_to_sheet(genderData);
        XLSX.utils.book_append_sheet(wb, genderSheet, '会员性别分布');

        const growthSheet = XLSX.utils.json_to_sheet(growthData);
        XLSX.utils.book_append_sheet(wb, growthSheet, '会员增长趋势');

        const courseSheet = XLSX.utils.json_to_sheet(courseData);
        XLSX.utils.book_append_sheet(wb, courseSheet, '课程预约次数');

        const coachSheet = XLSX.utils.json_to_sheet(coachData);
        XLSX.utils.book_append_sheet(wb, coachSheet, '教练预约次数');

        const equipmentSheet = XLSX.utils.json_to_sheet(equipmentData);
        XLSX.utils.book_append_sheet(wb, equipmentSheet, '设备数量');

        const cardSheet = XLSX.utils.json_to_sheet(cardData);
        XLSX.utils.book_append_sheet(wb, cardSheet, '卡种购买统计');

        const evaluateSheet = XLSX.utils.json_to_sheet(evaluateData.content);
        XLSX.utils.book_append_sheet(wb, evaluateSheet, '评价提交情况');

        const ratingSheet = XLSX.utils.json_to_sheet(ratingDistribution);
        XLSX.utils.book_append_sheet(wb, ratingSheet, '评价等级分布');

        const topContentsSheet = XLSX.utils.json_to_sheet(topContents);
        XLSX.utils.book_append_sheet(wb, topContentsSheet, '评价内容统计');

        XLSX.writeFile(wb, '数据报表.xls');
      }).catch((error) => {
        console.error('Error fetching data:', error);
      });
    },
  },
  mounted() {
    this.fetchDataForCurrentView();
  },
};
</script>

<style scoped>
.el-container {
  display: flex;
  height: 100vh;
}

.el-aside {
  background-color: #f3f4f6;
  color: #333;
  text-align: left;
}

.el-menu {
  border-right: none;
}

.el-menu-item {
  padding: 0 20px;
}

.main {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
  padding: 20px;
  background-color: #fff;
}

.report-content {
  width: 100%;
  max-width: 1200px;
}

h2 {
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}
</style>